using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using motion10.SharePoint.TwitterSupport.Common;
using Microsoft.Office.Server.UserProfiles;

namespace motion10.SharePoint.TwitterSupport.Features.motion10.SharePoint.TwitterSupport.PersonPage
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("66bde6c8-5875-456e-8994-2054f85c8352")]
    public class motion10SharePointTwitterSupportEventReceiver : SPFeatureReceiver
    {
        private const string TwitterScreenName = "Twitter ScreenName";
        private const string TwitterToken = "Twitter Token";
        private const string TwitterTokenSecret = "Twitter TokenSecret";
        private const string TwitterUserID = "Twitter UserID";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties == null)
                throw new ArgumentNullException("properties", "Argument 'properties' cannot be 'null'");

            using (SPWeb web = (SPWeb)properties.Feature.Parent)
            {
                SPWebApplication webApp = web.Site.WebApplication;
                SPServiceContext serviceContext = SPServiceContext.GetContext(webApp.ServiceApplicationProxyGroup, SPSiteSubscriptionIdentifier.Default);

                UserProfileConfigManager profileConfigManager = new UserProfileConfigManager(serviceContext);
                profileConfigManager.CreateProfileProperty(serviceContext, 250, TwitterScreenName, "string", Privacy.Private, false, false, false, true, false);
                profileConfigManager.CreateProfileProperty(serviceContext, 250, TwitterToken, "string", Privacy.Private, false, false, false, true, false);
                profileConfigManager.CreateProfileProperty(serviceContext, 250, TwitterTokenSecret, "string", Privacy.Private, false, false, false, true, false);
                profileConfigManager.CreateProfileProperty(serviceContext, 250, TwitterUserID, "string", Privacy.Private, false, false, false, true, false);

                StartServiceJob("User Profile Service", "UserProfile_ProfileSynchronizationJob", webApp);

                if (properties.Feature.Properties["ConsumerKey"] != null &&
                    properties.Feature.Properties["ConsumerSecret"] != null)
                {
                    SPWebExtensions.SetPropertyBagProperty(SPContext.Current.Web, Constants.PropertyBagConsumerKeyName, properties.Feature.Properties["ConsumerKey"].Value);
                    SPWebExtensions.SetPropertyBagProperty(SPContext.Current.Web, Constants.PropertyBagConsumerSecretName, properties.Feature.Properties["ConsumerSecret"].Value);
                }
                else
                {
                    throw new Exception("Unknow ConsumerKey & ConsumerSecret. Please provide these properties in the feature.xml");
                }
            }
        }

        private static void StartServiceJob(string serviceTypeName, string jobName, SPWebApplication webApp)
        {
            foreach (SPService service in webApp.Farm.Services)
            {
                if ((serviceTypeName != null) || (serviceTypeName == service.Name))
                {
                    foreach (SPJobDefinition jobDefinition in service.JobDefinitions)
                    {
                        if (jobDefinition.Name == jobName)
                        {
                            jobDefinition.RunNow();
                            break;
                        }
                    }
                }
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
